﻿using System;
using System.Globalization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace PictureSearch
{
    public partial class ImageItem
    {
        private static readonly SolidColorBrush selectBackGround = new SolidColorBrush(Colors.Purple);

        private const int defaultHeight = 300;
        private const int defaultWeidth = 480;

        public bool IsLoaded { get; private set; }

        public ImageItem(uint width, uint height)
        {
            InitializeComponent();

            this.txtWidth.Text = width.ToString(CultureInfo.InvariantCulture);
            this.txtHeight.Text = height.ToString(CultureInfo.InvariantCulture);

            this.Width = defaultWeidth;
            this.Height = defaultHeight;

            IsLoaded = false;
        }

        private void image_ImageFailed(object sender, ExceptionRoutedEventArgs e)
        {
            StackPanel sp = this.Parent as StackPanel;

            if (sp != null)
            {
                sp.Children.Remove(this);
            }
        }

        public void SetImageUrl(string uri)
        {
            this.Dispatcher.BeginInvoke(
                () =>
                {
                    this.image.Source = new BitmapImage(new Uri(uri));
                });
        }

        public void SetSelectedBackGround()
        {
            gridRoot.Background = gridRoot.Background == null ? selectBackGround : null;
        }

        private void image_ImageOpened(object sender, RoutedEventArgs e)
        {
            this.progressBar.IsIndeterminate = false;
            this.spLoading.Visibility = Visibility.Collapsed;

            IsLoaded = true;
        }
    }
}
